package com.kaichaohulian.baocms.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kaichaohulian.baocms.R;
import com.kaichaohulian.baocms.app.MyApplication;
import com.kaichaohulian.baocms.base.BaseActivity;
import com.kaichaohulian.baocms.http.HttpUtil;
import com.kaichaohulian.baocms.http.Url;
import com.kaichaohulian.baocms.qiniu.Auth;
import com.kaichaohulian.baocms.qiniu.QiNiuConfig;
import com.kaichaohulian.baocms.utils.DBLog;
import com.kaichaohulian.baocms.view.ShowDialog;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.apache.http.Header;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.kaichaohulian.baocms.activity.PersonalActivity.SET_HEADIMG;
import static com.kaichaohulian.baocms.activity.PersonalActivity.SET_PASSWORD_CODE;

/**
 * 实名认证界面
 */
public class RealnameActivity extends BaseActivity {


    @BindView(R.id.view_temp)
    View viewTemp;
    @BindView(R.id.exit_layout)
    LinearLayout exitLayout;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.center_title_tv)
    TextView centerTitleTv;
    @BindView(R.id.tv_right_text)
    TextView tvRightText;
    @BindView(R.id.iv_image)
    ImageView ivImage;
    @BindView(R.id.iv_image1)
    ImageView ivImage1;
    @BindView(R.id.navigation_bar)
    RelativeLayout navigationBar;
    @BindView(R.id.title_linLayout)
    LinearLayout titleLinLayout;
    @BindView(R.id.img_zhengmian)
    ImageView imgZhengmian;
    @BindView(R.id.fanmian)
    ImageView fanmian;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    @BindView(R.id.edit_realname)
    EditText editRealname;
    @BindView(R.id.edit_card)
    EditText editCard;
    private PopupWindow popWindow, popWindow2;

    private UploadManager uploadManager;

    @Override
    public void setContent() {
        setContentView(R.layout.activity_realname);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        setCenterTitle("实名认证");

    }

    @Override
    public void initEvent() {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.view_temp, R.id.exit_layout, R.id.fanmian,R.id.tv_title, R.id.center_title_tv, R.id.tv_right_text, R.id.iv_image, R.id.iv_image1, R.id.navigation_bar, R.id.title_linLayout, R.id.img_zhengmian, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.view_temp:
                break;
            case R.id.exit_layout:
                break;
            case R.id.tv_title:
                break;
            case R.id.center_title_tv:
                break;
            case R.id.tv_right_text:
                break;
            case R.id.iv_image:
                break;
            case R.id.fanmian:
                pacchoose=2;
                showPhotoDialog();
                break;
            case R.id.iv_image1:
                break;
            case R.id.navigation_bar:
                break;
            case R.id.title_linLayout:
                break;
            case R.id.img_zhengmian:
                pacchoose=1;
                showPhotoDialog();
                break;

            case R.id.btn_submit:
                if (TextUtils.isEmpty(editRealname.getText().toString().trim())) {
                    Toast.makeText(RealnameActivity.this, "请输入真实姓名", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(editCard.getText().toString().trim())) {
                    Toast.makeText(RealnameActivity.this, "请输入身份证号", Toast.LENGTH_SHORT).show();
                } else {
                    getsubmit();
                }

                break;
        }
    }

    private String imageName;
    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    //拍照或相册
    private void showPhotoDialog() {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.alertdialog);
        // 为确认按钮添加事件,执行退出应用操作
        TextView tv_paizhao = (TextView) window.findViewById(R.id.tv_content1);
        tv_paizhao.setText("拍照");
        tv_paizhao.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SdCardPath")
            public void onClick(View v) {
                imageName = getNowTime() + ".png";
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 指定调用相机拍照后照片的储存路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(MyApplication.getInstance().SAVE_PIC_PATH, imageName)));
                startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                dlg.cancel();
            }
        });
        TextView tv_xiangce = (TextView) window.findViewById(R.id.tv_content2);
        tv_xiangce.setText("相册");
        tv_xiangce.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                getNowTime();
                imageName = getNowTime() + ".png";
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                dlg.cancel();
            }
        });
    }

    //获取当前时间
    @SuppressLint("SimpleDateFormat")
    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSS");
        return dateFormat.format(date);
    }

    private void showPopupWindow(View parent) {
        if (popWindow == null) {
        /*    View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.pop_select_photo2, null)));*/
//ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) convertView);
//            LayoutInflater.from(this).inflate(R.layout.pop_select_photo2,null)
            View view = LayoutInflater.from(this).inflate(R.layout.pop_select_img, null);
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
//            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    private void showImageView(ImageView iamgeView, String avatar) {
        Glide.with(RealnameActivity.this)
                .load(avatar)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(iamgeView);
    }
    private int REQUEST_CODE = 200;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case PHOTO_REQUEST_TAKEPHOTO:
                    startPhotoZoom(Uri.fromFile(new File(MyApplication.getInstance().SAVE_PIC_PATH, imageName)), 480);
//                    showImageView(imgZhengmian,);

                    break;
                case PHOTO_REQUEST_GALLERY:
                    if (data != null)
                        startPhotoZoom(data.getData(), 480);
                    break;
                case PHOTO_REQUEST_CUT:
                    updateAvatarInServer(imageName);
                    break;

                case SET_PASSWORD_CODE:

                    break;
            }
        }
    }
   private void updateAvatarInServer(final String image) {
        ShowDialog.showDialog(getActivity(), "上传图片中...", false, null);
        File mFile = new File(MyApplication.getInstance().SAVE_PIC_PATH + image);
        if (mFile.exists()) {
            upload(getToken(), mFile);
        } else {
            ShowDialog.dissmiss();
            showToastMsg("获取图片异常");
        }
    }

    //获取TOKEN
    private String getToken() {
        Auth auth = Auth.create(QiNiuConfig.QINIU_AK, QiNiuConfig.QINIU_SK);
        return auth.uploadToken("yxin");
    }

    String picurl="",picurlback="";
    int pacchoose=0;


    //上传图片
    private void upload(String uploadToken, File uploadFile) {
        if (uploadManager == null) {
            uploadManager = new UploadManager();
        }
        uploadManager.put(uploadFile, null, uploadToken,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, final ResponseInfo respInfo, JSONObject jsonData) {
                        if (respInfo.isOK()) {
                            try {
                                String fileKey = jsonData.getString("key");
                                final String url = "http://oez2a4f3v.bkt.clouddn.com/" + fileKey;
                                if (pacchoose==1){
                                    picurl = url;
                                    showImageView(imgZhengmian,picurl);
                                }else if (pacchoose==2){
                                    picurlback = url;
                                    showImageView(fanmian,picurlback);
                                }
                            } catch (Exception e) {
                                showToastMsg("上传图片失败");
                            }finally {
                                ShowDialog.dissmiss();
                            }
                        } else {
                            ShowDialog.dissmiss();
                            showToastMsg("上传图片失败");
                        }
                    }
                }, null);
    }

    @SuppressLint("SdCardPath")
    private void startPhotoZoom(Uri uri1, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri1, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", false);

        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(MyApplication.getInstance().SAVE_PIC_PATH, imageName)));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    public void getsubmit() {

        RequestParams params = new RequestParams();
        params.put("id", MyApplication.getInstance().UserInfo.getUserId());
        params.put("cardNo", editCard.getText().toString().trim());
        params.put("name", editRealname.getText().toString().trim());
        params.put("pic1", picurl);
        params.put("pic2", picurlback);
        HttpUtil.post(Url.shiming, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Toast.makeText(RealnameActivity.this, "成功", Toast.LENGTH_SHORT).show();
                finish();
            }
            @Override
            public void onFinish() {
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToastMsg("请求服务器失败");
                DBLog.e("tag", statusCode + ":" + responseString);
            }
        });

    }


}


